/* 
 * cms，一个基于J2EE架构内容管理系统
 * Copyright © GrayRabbit Co., Ltd. All rights reserved.
 * Department:运营department
 * 更多信息请访问：
 * http://code.google.com/p/gray-rabbit-cms/
 */
package org.grayrabbit.cms.action.plugins;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.grayrabbit.cms.action.common.BaseAction;
import org.grayrabbit.cms.constant.ConstantWebApp;
import org.grayrabbit.cms.constant.DictionaryStaticValues;
import org.grayrabbit.cms.constant.ConstantEnum.Module;
import org.grayrabbit.cms.constant.ConstantEnum.OperAct;
import org.grayrabbit.cms.entity.Admin;
import org.grayrabbit.cms.entity.Dictionary;
import org.grayrabbit.cms.entity.Site;
import org.grayrabbit.cms.entity.SubjectOption;
import org.grayrabbit.cms.entity.Survey;
import org.grayrabbit.cms.entity.SurveySubject;
import org.grayrabbit.cms.service.dictionary.DictionaryService;
import org.grayrabbit.cms.service.plugins.SubjectOptionService;
import org.grayrabbit.cms.service.plugins.SurveyService;
import org.grayrabbit.cms.service.plugins.SurveySubjectService;
import org.grayrabbit.cms.vo.plugins.SurveyBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import org.grayrabbit.dao.util.Page;

/**
 * <b>SurveyAction</b> Struts2 action�?





 * @version 1.0,创建时间:2011-05-16 16:08:59 
 */
@Controller
@Scope("prototype")
@Results( {
		@Result(name = "reload", type = "redirect", location = "survey-list"),
		@Result(name = "input", type = "dispatcher", location = "survey-input.jsp"),
		@Result(name = "success", type = "dispatcher", location = "survey-list.jsp")	
		}
		)
public class SurveyAction extends BaseAction<SurveyBean> {
	private static final long serialVersionUID = -1L;
	public static final String SURVEY = "survey";
	//Service接口接入
	@Autowired
	@Qualifier("surveyServiceImpl")
	private SurveyService surveyService;
	@Autowired
	@Qualifier("surveySubjectServiceImpl")
	private SurveySubjectService surveySubjectService;
	@Autowired
	@Qualifier("dictionaryServiceImpl")
	private DictionaryService dictionaryService;
	@Autowired
	@Qualifier("subjectOptionServiceImpl")
	private SubjectOptionService subjectOptionService;
	
	private List<Dictionary> dicSurveyStatus;
	
	private List<Dictionary> dicSurveyRepeatSubmitStatus;
	
	private List<Dictionary> dicSurveyCheckType;
	
	private List<Dictionary> dicCheckModel;
	
	private List<SurveySubject> surSubList;
	
	private String surname;
	private String upId;
	
	public List<Dictionary> getDicSurveyStatus() {
		return dicSurveyStatus;
	}

	public void setDicSurveyStatus(List<Dictionary> dicSurveyStatus) {
		this.dicSurveyStatus = dicSurveyStatus;
	}

	public List<Dictionary> getDicSurveyRepeatSubmitStatus() {
		return dicSurveyRepeatSubmitStatus;
	}

	public void setDicSurveyRepeatSubmitStatus(
			List<Dictionary> dicSurveyRepeatSubmitStatus) {
		this.dicSurveyRepeatSubmitStatus = dicSurveyRepeatSubmitStatus;
	}

	public List<Dictionary> getDicSurveyCheckType() {
		return dicSurveyCheckType;
	}

	public void setDicSurveyCheckType(List<Dictionary> dicSurveyCheckType) {
		this.dicSurveyCheckType = dicSurveyCheckType;
	}
	//VO对象，由前端页面数据组装
	private SurveyBean survey;
	
	private String orig;
	
	private String sflag;
	
	private String subjects;
	//批量操作时使用的传入的ID
	
	
	private String[] optArray;
	
	private String[] ordArray;
	
	private String[] optIdArray;
	
	private String ids;
	
	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}
	
	public String getOrig() {
		return orig;
	}

	public void setOrig(String orig) {
		this.orig = orig;
	}
	/**return 前端页面数据组装VO对象,<b>SurveyBean</b>*/
	public SurveyBean getSurvey() {
		return survey;
	}

	public void setSurvey(SurveyBean survey) {
		this.survey = survey;
	}

	public String getSurveyId() {
		return surveyId;
	}

	public void setSurveyId(String surveyId) {
		this.surveyId = surveyId;
	}

	public String getSflag() {
		return sflag;
	}

	public void setSflag(String sflag) {
		this.sflag = sflag;
	}
	public List<SurveySubject> getSurSubList() {
		return surSubList;
	}

	public void setSurSubList(List<SurveySubject> surSubList) {
		this.surSubList = surSubList;
	}

	public String[] getOptArray() {
		return optArray;
	}

	public void setOptArray(String[] optArray) {
		this.optArray = optArray;
	}

	public String[] getOrdArray() {
		return ordArray;
	}

	public void setOrdArray(String[] ordArray) {
		this.ordArray = ordArray;
	}

	public String[] getOptIdArray() {
		return optIdArray;
	}

	public void setOptIdArray(String[] optIdArray) {
		this.optIdArray = optIdArray;
	}
	//分页对象
	private Page<Survey> page = new Page<Survey>(MAX_PAGE_NUM,true);
	
	/*
	 * return分页对象，默认实例化。如：page.pageNu=2,将更新相应的对象property
	 */
	public Page<Survey> getPage() {
		return page;
	}
	//接收前端form,url提交参数组装成分页property
	public void setPage(Page<Survey> page) {
		this.page = page;
	}
	
	/**
	 * 在执行（struts2的action调用时）list()方法前执行本方法
	 */
	public void prepareList(){
		if(dictionaryService.getDictionaryListByTypeCode(DictionaryStaticValues.SURVEYSTATUS)!=null){
			dicSurveyStatus = dictionaryService.getDictionaryListByTypeCode(DictionaryStaticValues.SURVEYSTATUS);
		}
		prepareModel();
	}
	
	/**
	 * 在执行任何其它action方法（struts2的action调用时）前执行本方法
	 */
	public void prepare(){
		if(survey==null){
			survey = new SurveyBean();
		}
	}
	/**
	 * 实现ModelDriven的接口简例前端页的bean组装写法,
	 *  如：
	 *	<pre>
	 *		<code> name="user.userName"</code>
	 *	改写成：
	 *		<code> name="userName"</code>
	 *	action实例中，会自动组成user成员变量
	 *	</pre>
	 */
	public SurveyBean getModel() {
		return survey;
	}
	
	@Override
	protected void prepareModel(){
		if(survey != null && StringUtils.isNotBlank(survey.getSurveyId())){
			Survey item = surveyService.getSurvey(survey.getSurveyId());
			survey = (SurveyBean)dozer.map(surveyService.getSurvey(survey.getSurveyId()),SurveyBean.class);
			survey.setSite(item.getSite());
			surSubList = surveySubjectService.findBySurveyId(survey.getSurveyId());
		}
		
	}
	
	/**
	 * 删除<b>Survey</b>记录的方法，成员变量<b>key</b>为主键的String数组，以主键方式进行删作
	 * 删除成功后，返回"reload"，然后跳转到survey-list.action
	 */
	@Override
	@Action(value="survey-delete",
			results={@Result(name="reload",type="redirectAction",params={"actionName","survey-list"})}
			)
	public String delete(){
		String[] idBatchs=getBatchIds();
		if(idBatchs != null){
			for(int i=0;i<idBatchs.length;i++){
				List<SurveySubject> list = surveySubjectService.findBySurveyId(idBatchs[i]);
				String[] subIds = new String[list.size()];
				for(int k=0;k<list.size();k++){
					subIds[k] = list.get(k).getSubjectId();
					List<SubjectOption> optList = subjectOptionService.findBySubjectId(subIds[k]);
					String[] optIds = new String[optList.size()];
					for(int j=0;j<optList.size();j++){
						optIds[j] = optList.get(j).getOptionId();
					}
					subjectOptionService.delete(optIds);
				}
				surveySubjectService.delete(subIds);
			}
			surveyService.delete(idBatchs);
			for(int i=0;i<idBatchs.length;i++){
				addLog(Module.PLUGIN.getValue(),OperAct.DEL.getValue(),idBatchs[i]);
			}
		}else{
			List<SurveySubject> list = surveySubjectService.findBySurveyId(key[0]);
			String[] subIds = new String[list.size()];
			for(int i=0;i<list.size();i++){
				subIds[i] = list.get(i).getSubjectId();
				List<SubjectOption> optList = subjectOptionService.findBySubjectId(subIds[i]);
				String[] optIds = new String[optList.size()];
				for(int j=0;j<optList.size();j++){
					optIds[j] = optList.get(j).getOptionId();
				}
				subjectOptionService.delete(optIds);
			}
			surveySubjectService.delete(subIds);
			surveyService.delete(key);
			addLog(Module.PLUGIN.getValue(),OperAct.DEL.getValue(),key[0]);
		}
		return RELOAD;
	}
	/**
	 * 批量操作，ID处理
	 * @return
	 */
	private String[] getBatchIds(){
		String[] idBatchs=null;
		if((null!=ids)&&(StringUtils.isNotBlank(ids))){
			if(ids.startsWith("on@")){
				String allId = ids.substring(ids.indexOf("@")+1);
				idBatchs=allId.split("@");
			}else{
				idBatchs=ids.split("@");
			}
		}
		return idBatchs;
	}
	/**
	 * Survey的列表方法，通过成员变量<b>page�?{insClassName}</b>调用service接口，更新page
	 * 执行成功后，将映射到survey-list.jsp页面
	 */
	@Override
	@Action(value="survey-list")
	public String list(){
		Site currentSite = (Site)getSessionValue(ConstantWebApp.CURRENT_SITE);
		if(currentSite!=null && StringUtils.isNotBlank(currentSite.getSiteId())){
			survey.setSite(currentSite);
			if(StringUtils.isNotBlank(survey.getIsEnebleForPage())){
				survey.setSurveyStatus(survey.getIsEnebleForPage().equals("true")?true:false);
			}
			surveyService.list(page,survey);
			return SUCCESS;
		}else{
			return ERROR;
		}
	}
	/**
	 * Survey的新增与编辑的方法执行成功能
	 * 将映射到survey-input.jsp
	 */
	@Action(value="survey-input")
	public String input(){
		if(dictionaryService.getDictionaryListByTypeCode(DictionaryStaticValues.SURVEYSTATUS)!=null){
			dicSurveyStatus = dictionaryService.getDictionaryListByTypeCode(DictionaryStaticValues.SURVEYSTATUS);
		}
		if(dictionaryService.getDictionaryListByTypeCode(DictionaryStaticValues.SURVEYREPEATSUBMITSTATUS)!=null){
			dicSurveyRepeatSubmitStatus = dictionaryService.getDictionaryListByTypeCode(DictionaryStaticValues.SURVEYREPEATSUBMITSTATUS);
		}
		if(dictionaryService.getDictionaryListByTypeCode(DictionaryStaticValues.IS_CHECKMODEL)!=null){
			dicCheckModel = dictionaryService.getDictionaryListByTypeCode(DictionaryStaticValues.IS_CHECKMODEL);
		}
		
		prepareModel();
		return INPUT;
	}
	
	/**
	 * save or update Survey的方法，将成员property survey转成Survey实例，执行保存；
	 * 执行成功后，返回"reload"，然后跳转到survey-list.action
	 */
	@Override
	@Action(value="survey-save",
			results={@Result(name="reload",type="redirectAction",params={"actionName","surveysubject-input?survey.surveyId=${surveyId}"}),
					 @Result(name="survey",type="redirectAction",params={"actionName","survey-list"})}
		)
	public String save(){
		Survey item = null;
		Survey obj = null;
		if(StringUtils.isNotBlank(survey.getSurveyId())){
			 item = surveyService.getSurvey(survey.getSurveyId());
			 obj = (Survey) dozer.map(survey, Survey.class);
			 obj.setSite(item.getSite());
		}else{
			 obj = (Survey) dozer.map(survey, Survey.class);
		}
		
		if(!StringUtils.isNotBlank(obj.getSurveyId())){
			obj.setSurveyId(null);
		}
		if(!StringUtils.isNotBlank(obj.getSurveyId())){
			if(!surList().isEmpty() && surList().get(0).getOrd() != null) {
				obj.setOrd(surList().get(0).getOrd() + 1);
			}else {
				obj.setOrd(1);
			}
		}
		Admin admin = getCurrentAdmin();
		Site currentSite = (Site)getSessionValue(ConstantWebApp.CURRENT_SITE);
		if(StringUtils.isBlank(survey.getSurveyId())){
			obj.setSite(currentSite);
			obj.setCreateTime(new Date());
			if(admin != null){
				obj.setCreateLoginName(admin.getLoginName());
				obj.setCreateRealName(admin.getRealName());
			}
		}else{
			obj.setUpdateTime(new Date());
			if(admin != null){
				obj.setUpdateLoginName(admin.getLoginName());
				obj.setUpdateRealName(admin.getRealName());
			}
		}
		surveyService.save(obj);
		setSurveyId(obj.getSurveyId());
		
		if(StringUtils.isBlank(survey.getSurveyId())){
			addLog(Module.PLUGIN.getValue(),OperAct.ADD.getValue(),obj.getSurveyId());
		}else{
			addLog(Module.PLUGIN.getValue(),OperAct.ADD.getValue(),survey.getSurveyId());
		}
		
		
			//调查科目添加
			String [] optionArr = null;
			optionArr = optArray[0].split(",");
			String [] ordsArr = null;
			ordsArr = ordArray[0].split(",");
			String [] idArray = null;
			idArray = optIdArray[0].split(",");
			
			String[] subs=null;
			String[] sub = null;
			String[] subtc = null;
			String[] opts = null;
			String[] subb = null;
			String[] opttitle = null;
			String[] optid = null;
			if(StringUtils.isNotBlank(survey.getSurveyId())){
				if(subjects != null && !subjects.equals("")){
					subs = subjects.split("@");
					for(int i=0;i<subs.length;i++){
						sub = subs[i].split("#");
						subb = sub[0].split("%");
						 subtc = subb[0].split("!");
						 String	subTile = subtc[0];// 得到科目标题
						 String subChekM = subtc[1];
						 SurveySubject voptionobj = new SurveySubject();
						 if(subb.length<=1){
							 voptionobj.setSubjectTitle(subTile);
							 boolean cm = Boolean.valueOf(subChekM).booleanValue();
							 voptionobj.setSubjectCheckModel(cm);
							 if(ordsArr.length == optionArr.length){
								 for(int j=0;j<optionArr.length;j++){
									 if(optionArr[j].equals(subTile)){
											 voptionobj.setOrd(Integer.parseInt(ordsArr[j]));
									 }
								 }
							 }
							 voptionobj.setSurvey(new Survey(survey.getSurveyId()));
							 surveySubjectService.save(voptionobj);
						 }else{
							 String subId = subb[1];// 得到科目Id
							 SurveySubject vo = surveySubjectService.getSurveySubject((subId));
							 if(!vo.getSubjectTitle().equals(subTile)){
								 vo.setSubjectTitle(subTile);
							 }
							 for(int j=0;j<optArray.length;j++){
								 if(optArray[j].equals(subTile)){
									 if(!vo.getOrd().equals(ordsArr[j])){
										 vo.setOrd(Integer.parseInt(ordsArr[j]));
									 }
								 }
							 }
							 surveySubjectService.save(vo);
						 }
						 
						 opts = sub[1].split("&");
						 opttitle = opts[0].split("!");//得到答案项标题数组
						 if(opts.length <= 1){
							 for(int t=0;t<opttitle.length;t++){
								   SubjectOption so= new SubjectOption();
								   so.setOptionTitle(opttitle[t]);
									so.setSurveySubject(new SurveySubject(voptionobj.getSubjectId()));
									subjectOptionService.save(so);
							   }
						 }else{
							 optid = opts[1].split("!!");//得到答案项ID数组
							 if(optid.length<opttitle.length){
								 for(int k=0;k<opttitle.length;k++){
									 if(k<opttitle.length-optid.length){
										 SubjectOption so= new SubjectOption();
										   so.setOptionTitle(opttitle[k]);
										   so.setSurveySubject(new SurveySubject(subb[1]));
										   subjectOptionService.save(so);
									 }else{
										 SubjectOption so = subjectOptionService.getSubjectOption(optid[k-(opttitle.length-optid.length)]);
										 if(!so.getOptionTitle().equals(opttitle[k])){
											 so.setOptionTitle(opttitle[k]);
										 }
										 subjectOptionService.save(so);
									 }
								 }
							 }else if(optid.length>opttitle.length){
								 for(int k=0;k<optid.length;k++){
									 if(k<optid.length-opttitle.length){
										 String[] oid = new String[1];
										 oid[0]=optid[k];
										 subjectOptionService.delete(oid);
									 }else{
										 SubjectOption so = subjectOptionService.getSubjectOption(optid[k]);
										 if(!so.getOptionTitle().equals(opttitle[k-(optid.length-opttitle.length)])){
											 so.setOptionTitle(opttitle[k-(optid.length-opttitle.length)]);
										 }
										 subjectOptionService.save(so);
									 }
								 }
							 }else{
								 for(int j=0;j<optid.length;j++){
										 SubjectOption so = subjectOptionService.getSubjectOption(optid[j]);
										 if(!so.getOptionTitle().equals(opttitle[j])){
											 so.setOptionTitle(opttitle[j]);
										 }
										 subjectOptionService.save(so);
								 }
							 }
						 }
					}
				}else{
					if(optionArr!= null && optionArr.length>0){
						for(int i=0;i<optionArr.length;i++){
							SurveySubject vo = surveySubjectService.getSurveySubject((idArray[i]));
							if(!vo.getSubjectTitle().equals(optionArr[i])){
								vo.setSubjectTitle(optionArr[i]);
							}
							if( optionArr.length == ordsArr.length){
								vo.setOrd(Integer.parseInt(ordsArr[i]));
							}
							surveySubjectService.save(vo);
						}
					}
				}
		}else{//新增科目及答案项
			if(subjects != null && !subjects.equals("")){
					subs = subjects.split("@");
					for(int i=0;i<subs.length;i++){
						sub = subs[i].split("#");
						 subtc = sub[0].split("!");
						 String	sutTile = subtc[0];// 得到科目标题
						 String subChekM = subtc[1];
						   SurveySubject voptionobj = new SurveySubject();
						   voptionobj.setSubjectTitle(sutTile);
						   boolean cm = Boolean.valueOf(subChekM).booleanValue();
							 voptionobj.setSubjectCheckModel(cm);
						   if(!ordsArr[i].equals("")&& ordsArr[i] != null){
								voptionobj.setOrd(Integer.parseInt(ordsArr[i]));
							}
						   voptionobj.setSurvey(new Survey(obj.getSurveyId()));
						   surveySubjectService.save(voptionobj);
						   opts = sub[1].split("!");
						   for(int t=0;t<opts.length;t++){
							   SubjectOption so= new SubjectOption();
							   so.setOptionTitle(opts[t]);
								so.setSurveySubject(new SurveySubject(voptionobj.getSubjectId()));
								subjectOptionService.save(so);
						   }
					}
			}	
		}
		if(sflag.equals("sflag")){
			return RELOAD;
		}else{
			return SURVEY;
		}
	}

	private String surveyId;
	
	/**
	 * 禁用/启用 调查
	 * @return
	 */
	@Action(value="survey-disableorenable")
	public String disableOrEnable(){
		String text="";
		Survey obj=null;
		try {
			if(null!=survey&&StringUtils.isNotBlank(survey.getSurveyId())){
				obj = surveyService.getSurvey(survey.getSurveyId());
				if(null!=obj.getSurveyStatus()&&!obj.getSurveyStatus()){
					obj.setSurveyStatus(true);
					addLog(Module.PLUGIN.getValue(),OperAct.ENABLE.getValue(),survey.getSurveyId());
				}else{
					obj.setSurveyStatus(false);
					addLog(Module.PLUGIN.getValue(),OperAct.DISABLE.getValue(),survey.getSurveyId());
				}
				surveyService.save(obj);
			}
			text="ok";
		} catch (Exception e) {
			log.debug(e.getMessage());
			text="no";
			
		}
		return renderText(text);
	}
	
	/**
	 * 批量禁用
	 */
	@Action(value="survey-batchdisable")
	public String batchDisable(){
		String text="";
		try {
			String[] idBatchs=getBatchIds();
			surveyService.disable(idBatchs);
			for(int i=0;i<idBatchs.length;i++){
				addLog(Module.PLUGIN.getValue(),OperAct.DISABLE.getValue(),idBatchs[i]);
			}
			text="ok";
		} catch (Exception e) {
			text="no";
			log.debug(e.getMessage());
		}
		return renderText(text);
	}
	/**
	 * 批量启用
	 */
	@Action(value="survey-batchenable")
	public String batchEnable(){
		String text="";
		try {
			String[] idBatchs=getBatchIds();
			surveyService.enable(idBatchs);
			for(int i=0;i<idBatchs.length;i++){
				addLog(Module.PLUGIN.getValue(),OperAct.ENABLE.getValue(),idBatchs[i]);
			}
			text="ok";
		} catch (Exception e) {
			text="no";
			log.debug(text);
		}
		return renderText(text);
	}
	/**
	 * 唯一验证
	 * @return
	 */
	@Action(value="survey-checknameunique")
	public String  checkNameUnique(){
		String text="";
		try{
			Site currentSite = (Site)getSessionValue(ConstantWebApp.CURRENT_SITE);
			Boolean unique=surveyService.checkNameUnique(survey.getSurveyTitle().trim(),surname,currentSite.getSiteId());
			if(!unique){
				text="ok";
			}else{
				text="no";
			}
		}catch(Exception e){
			text="no";
		}
		return renderText(text);
	}
	/**
	 * 上移
	 */
	@Action(value="survey-upmove")
	public String upmove() {
		Survey obj = null;
		Survey upObj = null;
		if(survey != null && StringUtils.isNotBlank(survey.getSurveyId())) {
			obj = surveyService.getSurvey(survey.getSurveyId());
			upObj = surveyService.getSurvey(upId);
			Integer cord = obj.getOrd();
			Integer uord = upObj.getOrd();
			obj.setOrd(uord);
			upObj.setOrd(cord);
			surveyService.save(obj);
			surveyService.save(upObj);
		}
		return null;
	}
	
	/**
	 * 下移
	 */
	@Action(value="survey-downmove")
	public String downmove() {
		Survey obj = null;
		Survey upObj = null;
		if(survey != null && StringUtils.isNotBlank(survey.getSurveyId())) {
			obj = surveyService.getSurvey(survey.getSurveyId());
			upObj = surveyService.getSurvey(upId);
			Integer cord = obj.getOrd();
			Integer uord = upObj.getOrd();
			obj.setOrd(uord);
			upObj.setOrd(cord);
			surveyService.save(obj);
			surveyService.save(upObj);
		}
		return null;
	}
	
	private List<Survey> surList(){
		List<Survey> list = surveyService.surList();
		return list;
	}

	public String getSubjects() {
		return subjects;
	}

	public void setSubjects(String subjects) {
		this.subjects = subjects;
	}

	public List<Dictionary> getDicCheckModel() {
		return dicCheckModel;
	}

	public void setDicCheckModel(List<Dictionary> dicCheckModel) {
		this.dicCheckModel = dicCheckModel;
	}

	public String getSurname() {
		return surname;
	}

	public void setSurname(String surname) {
		this.surname = surname;
	}

	public String getUpId() {
		return upId;
	}

	public void setUpId(String upId) {
		this.upId = upId;
	}
}